/**
 *
 */
package anysware.source;

import java.io.File;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AgeFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import anysware.file.FileItem;
import anysware.file.FileItemService;

/**
 * TODO: doc me
 *
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 111 $
 * @version
 */
public class FileSourceSync {
	private static final Logger	LOG	= LoggerFactory
	                                        .getLogger(FileSourceSync.class);
	private FileItemService	    fileItemService;
	private SourceService	    sourceService;

	/**
	 * @param fileItemService
	 *            the fileItemService to set
	 */
	public void setFileItemService(final FileItemService fileItemService) {
		this.fileItemService = fileItemService;
	}

	/**
	 * @param sourceService
	 *            the sourceService to set
	 */
	public void setSourceService(final SourceService sourceService) {
		this.sourceService = sourceService;
	}

	@SuppressWarnings("unchecked")
	public void sync() {
		final Collection<Source> sources = sourceService
		        .getSourceByType("anysware:source:file");
		for (final Source source : sources) {
			try {
				final File root = new File(source.getPath().toURI());
				IOFileFilter filter = null;
				if (source.getLastChecked() == null) {
					filter = TrueFileFilter.INSTANCE;
				} else {
					filter = new AgeFileFilter(source.getLastChecked(), false);
				}
				final Collection<File> files = FileUtils.listFiles(root,
				        filter, TrueFileFilter.INSTANCE);
				for (final File file : files) {
					fileItemService.save(new FileItem(file, source));
				}
				source.setLastModified(new Date(root.lastModified()));
				source.setLastChecked(new Date());
				sourceService.save(source);
				if (LOG.isInfoEnabled()) {
					LOG.info("Source [{} - {}] was synced", new Object[] {
					        source.getName(), source.getPath() });
				}
			} catch (final URISyntaxException e) {
				if (LOG.isErrorEnabled()) {
					LOG.error(e.getMessage(), e);
				}
			}

		}
	}
}
